package com.example.interceptor;

import com.example.entity.auth.UserInfo;
import com.example.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AccountInterceptor implements HandlerInterceptor {
    @Resource
    UserMapper mapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SecurityContext context = SecurityContextHolder.getContext(); // 获取当前安全上下文
        Authentication authentication = context.getAuthentication(); // 获取当前登录用户信息
        String username = authentication.getName(); // 获取当前登录用户名
        UserInfo userInfo = mapper.findUserInfoByNameOrEmail(username); // 根据用户名查询用户信息
        request.getSession().setAttribute("userInfo", userInfo); // 将用户信息存储到session中
        return true;
    }
}
